<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="维修类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择维修类型" clearable style="width: 200px;">
          <el-option v-for="type in repairTypes" :key="type" :label="type" :value="type" />
        </el-select>
      </el-form-item>
      <el-form-item label="车主姓名" prop="uid">
        <el-select v-model="queryParams.uid" placeholder="请选择用户" style="width: 200px;" @keyup.enter="handleQuery">
          <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间" prop="reservationTime">
        <el-date-picker clearable
          v-model="queryParams.reservationTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约时间" style="width:200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="取车位置" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入取车位置"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item label="车辆类型" prop="carTypeId">
        <el-select v-model="queryParams.carTypeId" placeholder="请选择车辆类型" clearable @change="handleQuery" style="width: 200px;">
          <el-option v-for="carModel in carModels" :key="carModel.id" :label="carModel.name" :value="carModel.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="车牌编号" prop="carNum">
        <el-input
          v-model="queryParams.carNum"
          placeholder="请输入车牌编号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item label="维修状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择维修状态" clearable style="width:200px;">
          <el-option v-for="status in repairStatuses" :key="status.value" :label="status.label" :value="status.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['chy:reservation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['chy:reservation:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['chy:reservation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['chy:reservation:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reservationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="维修类型" align="center" prop="type" width="100">
        <template #default="scope">
          <el-tag type="warning">{{ scope.row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="车主姓名" align="center">
        <template #default="scope">
          {{ getUserNameById(scope.row.uid) }}
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" width="120">
        <template #default="scope">
          {{ getUserPhoneById(scope.row.uid) }}
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="reservationTime" width="110">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reservationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="取车位置" align="center" prop="location" />
      <el-table-column label="车辆类型" align="center" prop="carTypeId">
        <template #default="scope">
          <el-tag type="success">
            {{ getCarModelNameById(scope.row.carTypeId) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="车牌编号" align="center" prop="carNum" width="110">
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.carNum }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="整车照片" align="center" prop="vehiclePhotos">
        <template #default="scope">
          <image-preview :src="scope.row.vehiclePhotos" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="维修照片" align="center" prop="repairPhotos">
        <template #default="scope">
          <image-preview :src="scope.row.repairPhotos" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="维修状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['chy:reservation:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['chy:reservation:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维修预约对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="reservationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="维修类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择维修类型">
            <el-option v-for="type in repairTypes" :key="type" :label="type" :value="type" />
          </el-select>
        </el-form-item>
        <el-form-item label="车主姓名" prop="uid">
          <el-select v-model="form.uid" placeholder="请选择用户" @change="fillUserNameAndCarNums">
            <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="form.name" placeholder="自动填充用户姓名" disabled/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" disabled/>
        </el-form-item>
        <el-form-item label="预约时间" prop="reservationTime">
          <el-date-picker clearable
            v-model="form.reservationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="取车位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入取车位置" />
        </el-form-item>
        <el-form-item label="车牌编号" prop="carNum">
          <el-select
            v-model="form.carNum"
            placeholder="请选择车牌号"
            :disabled="!form.uid"
            @change="fillCarType"
          >
            <el-option v-for="carNum in availableCarNums" :key="carNum" :label="carNum" :value="carNum" />
          </el-select>
          <el-tag v-if="form.carNum" closable @close="clearCarNum" style="margin-top: 5px;">
            {{ form.carNum }}
          </el-tag>
        </el-form-item>
        <el-form-item label="车辆类型" prop="carTypeId">
          <el-select v-model="form.carTypeId" placeholder="请选择车辆类型" clearable :disabled="true">
            <el-option v-for="carModel in carModels" :key="carModel.id" :label="carModel.name" :value="carModel.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="整车照片" prop="vehiclePhotos">
          <image-upload v-model="form.vehiclePhotos" />
        </el-form-item>
        <el-form-item label="维修照片" prop="repairPhotos">
          <image-upload v-model="form.repairPhotos" />
        </el-form-item>
        <el-form-item label="维修状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择维修状态">
            <el-option v-for="status in repairStatuses" :key="status.value" :label="status.label" :value="status.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Reservation">
import { listReservation, getReservation, delReservation, addReservation, updateReservation } from "@/api/chy/reservation"
import { listUsers } from "@/api/gas/users"
import { listUsercarinfo } from "@/api/chy/usercarinfo"

const { proxy } = getCurrentInstance()

const reservationList = ref([])
const usersList = ref([])
const usercarinfoList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const availableCarNums = ref([]) // 存储当前车主可用的车牌编号

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    name: null,
    phone: null,
    reservationTime: null,
    location: null,
    carTypeId: null,
    carNum: null,
    vehiclePhotos: null,
    repairPhotos: null,
    status: null,
    uid: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)
const repairTypes = ref([
  "到店维修",
  "上门维修",
])
const carModels = ref([
  { id: 1, name: "轿车" },
  { id: 2, name: "SUV" },
  { id: 3, name: "MPV" },
  { id: 4, name: "跑车" },
  { id: 5, name: "皮卡" },
  { id: 6, name: "旅行车" },
  { id: 7, name: "越野" },
  { id: 8, name: "微面" }
])
const repairStatuses = ref([
  { value: 1, label: '待处理', type: 'info' },
  { value: 2, label: '维修中', type: 'primary' },
  { value: 3, label: '已完成', type: 'success' },
  { value: 4, label: '已取消', type: 'danger' }
])

// 根据状态值获取状态标签
function getStatusLabel(status) {
  const statusObj = repairStatuses.value.find(s => s.value === status)
  return statusObj ? statusObj.label : '未知状态'
}

// 根据状态值获取 tag 类型
function getTagType(status) {
  const statusObj = repairStatuses.value.find(s => s.value === status)
  return statusObj ? statusObj.type : 'default'
}
/** 查询维修预约列表 */
function getList() {
  loading.value = true
  listReservation(queryParams.value).then(response => {
    reservationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getListUsers() {
  loading.value = true
  queryParams.value.params = {}
  listUsers(queryParams.value).then(response => {
    usersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
/** 查询用户车辆列表 */
function getListUsersCars() {
  loading.value = true
  listUsercarinfo(queryParams.value).then(response => {
    usercarinfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getUserNameById(uid) {
  const user = usersList.value.find(user => user.id == uid)
  return user ? user.userName : '未知用户'
}
function getUserPhoneById(uid) {
  const user = usersList.value.find(user => user.id == uid)
  return user? user.phone : '未知用户'
}
function getCarModelNameById(carTypeId) {
  const carModel = carModels.value.find(item => item.id === carTypeId)
  return carModel ? carModel.name : '未知类型'
}
// 定义填充用户姓名、手机号码和车牌编号的函数
function fillUserNameAndCarNums(uid) {
  const user = usersList.value.find(user => user.id === uid)
  if (user) {
    form.value.name = user.userName
    form.value.phone = user.phone
    // 筛选出当前车主的车牌编号
    availableCarNums.value = usercarinfoList.value
      .filter(item => item.uid === uid)
      .map(item => item.carNum)
  } else {
    form.value.name = ''
    form.value.phone = ''
    availableCarNums.value = []
  }
  // 无论是否找到用户，都清空车牌编号选择
  form.value.carNum = null
}
// 根据选中的车牌编号填充车辆类型
function fillCarType(carNum) {
  const carInfo = usercarinfoList.value.find(item => item.carNum === carNum);
  if (carInfo) {
    // 从 carModels 中查找对应的 carTypeId
    const carModel = carModels.value.find(model => model.name === carInfo.type);
    if (carModel) {
      form.value.carTypeId = carModel.id;
    } else {
      form.value.carTypeId = null;
    }
  } else {
    form.value.carTypeId = null;
  }
}

// 更新车牌编号 tag
function updateCarNumTag(carNum) {
  form.value.carNum = carNum
}

// 清除车牌编号选择
function clearCarNum() {
  form.value.carNum = null
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    name: null,
    phone: null,
    reservationTime: null,
    location: null,
    carTypeId: null,
    carNum: null,
    vehiclePhotos: null,
    repairPhotos: null,
    status: null,
    deleted: null,
    uid: null
  }
  proxy.resetForm("reservationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加维修预约"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getReservation(_id).then(response => {
    form.value = response.data
    // 调用 fillUserNameAndCarNums 函数加载该用户名下所有车牌编号
    fillUserNameAndCarNums(form.value.uid)
    // 确保在填充可用车牌编号后，设置当前车牌编号
    nextTick(() => {
      form.value.carNum = response.data.carNum
      // 填充车辆类型
      fillCarType(form.value.carNum)
    })
    open.value = true
    title.value = "修改维修预约"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["reservationRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateReservation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addReservation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除维修预约编号为"' + _ids + '"的数据项？').then(function() {
    return delReservation(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('chy/reservation/export', {
    ...queryParams.value
  }, `reservation_${new Date().getTime()}.xlsx`)
}

getList()
getListUsers()
getListUsersCars()
</script>
